#!/usr/bin/env python

import time
import component

from .._console import Console as Base

class Console(Base):

    def loadCamera(self):
        device = self._args.device
        self.progress('Loading camera at index %s... ' % device)
        try:
            self.camera = component.Camera(devnum=device)
            self.success('OK ^_^\n')
            result = True
        except:
            self.fail('Error >_<\n')
            result = False
        
        return result
    
    def setResolution(self):
        width = self._args.width
        height = self._args.height
        if not (width and height): return True
    
        s = 'Setting resolution to %sx%s pixels... '
        self.progress(s % (width, height))
        try:
            self.camera.setResolution(width, height)
            self.success('OK ^_^\n')
            result = True
        except:
            self.fail('Error >_<\n')
            result = False
        
        return result
        
    def saveSnapshot(self, resized):
        """Save snapshot to disk.
        
        Args:
            resized: A boolean indicating if the image already resized.
        """
        
        self.progress('Capturing image... ')
        
        start = time.time()
        try:
            while True:
                image = self.camera.getImage()
                if time.time() - start > self._args.delay: break
                
            self.success('OK ^_^\n')
            result = True
        except:
            self.fail('Error >_<\n')
            result = False
            
        if result:
            if not resized:
                size = (self._args.width, self._args.height)
                self.progress('Resizing image to %sx%s pixels... ' % size)
                image = image.resize(size)
                self.success('OK ^_^\n')
            name = '%s.jpg' % self._args.sequence
            self.progress('Saving snapshot as %s to disk... ' % name)
            try:
                image.save(name)
                self.success('OK ^_^\n')
            except:
                self.fail('Error >_<\n')
                
        return result
    